package com.zlyx.easy.swagger.helpers;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;

import org.springframework.core.annotation.AnnotationUtils;

import com.fasterxml.classmate.ResolvedType;
import com.fasterxml.classmate.TypeResolver;
import com.google.common.base.Function;
import com.google.common.base.Optional;

import io.swagger.annotations.ApiModelProperty;

public final class ApiModelProperties {

	public static Function<ApiModelProperty, ResolvedType> toType(final TypeResolver resolver) {
		return new Function<ApiModelProperty, ResolvedType>() {
			@Override
			public ResolvedType apply(ApiModelProperty annotation) {
				try {
					return resolver.resolve(Class.forName(annotation.dataType()));
				} catch (ClassNotFoundException e) {
					return resolver.resolve(Object.class);
				}
			}
		};
	}

	public static Optional<ApiModelProperty> findApiModePropertyAnnotation(AnnotatedElement annotated) {
		Optional<ApiModelProperty> annotation = Optional.absent();

		if (annotated instanceof Method) {
			annotation = Optional
					.fromNullable(AnnotationUtils.findAnnotation(((Method) annotated), ApiModelProperty.class));
		}

		return annotation.or(Optional.fromNullable(AnnotationUtils.getAnnotation(annotated, ApiModelProperty.class)));
	}
}
